/**
 *  插件
 */
layui.define(['layer', 'laytpl', 'form', 'element', 'upload', 'util'], function (exports) {

    var $ = layui.jquery
        , form = layui.form
        , layer = layui.layer
        , upload = layui.upload
        , util = layui.util
        , device = layui.device()

        , DISABLED = 'layui-btn-disabled';

    //阻止IE7以下访问
    if (device.ie && device.ie < 10) {
        layer.alert('如果您非得使用 IE 浏览器访问Fly社区，那么请使用 IE10+');
    }

    layui.focusInsert = function (obj, str) {
        var result, val = obj.value;
        obj.focus();
        if (document.selection) { //ie
            result = document.selection.createRange();
            document.selection.empty();
            result.text = str;
        } else {
            result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
            obj.focus();
            obj.value = result.join('');
        }
    };

    // 文本编辑器封装
    var fly = {

        dir: base + '/assets/plugins/layui/lay/modules/' //模块路径
        // 房间 右键菜单
        , layDropdownRoom: function () {

        }
        //简易编辑器
        , layEditor: function (options) {
            var html = ['<div class="layui-unselect fly-edit lay-room-list">'
                , '<span type="face" title="表情"><i class="layui-icon">&#xe650;</i></span>'
                , '<span type="picture" title="图片：img[src]"><i class="layui-icon">&#xe64a;</i></span>'
                , '<span type="picture" title="文件：img[src]"><i class="layui-icon">&#xe655;</i></span>'
                , '<span type="picture" title="音频：img[src]"><i class="layui-icon">&#xe6fc;</i></span>'
                , '<span type="picture" title="视频：img[src]"><i class="layui-icon">&#xe6ed;</i></span>'
                , '<span type="href" title="超链接格式：a(href)[text]"><i class="layui-icon">&#xe64c;</i></span>'
                // , '<span type="quote" title="引用"><i class="iconfont icon-yinyong" style="top: 1px;"></i></span>'
                , '<span type="code" title="插入代码" class="layui-hide-xs"><i class="layui-icon">&#xe64e;</i></span>'
                , '<span type="hr" title="水平线">hr</span>'
                , '<span type="preview" title="消息记录"><i class="layui-icon">&#xe60e;</i></span>'
                , '</div>'].join('');

            var closeTips = function () {
                layer.close(mod.face.index);
            };

            var log = {}, mod = {
                face: function (editor, self) { //插入表情
                    var str = '', ul, face = fly.faces;
                    for (var key in face) {
                        str += '<li title="' + key + '"><img src="' + face[key] + '"></li>';
                    }
                    str = '<ul id="LAY-editface" class="layui-clear" style="margin: -10px 0 0 -1px;">' + str + '</ul>';

                    layer.close(mod.face.index);
                    mod.face.index = layer.tips(str, self, {
                        tips: 3
                        , time: 0
                        , skin: 'layui-edit-face'
                        , tipsMore: true
                    });

                    $(document).off('click', closeTips).on('click', closeTips);

                    $('#LAY-editface li').on('click', function () {
                        var title = $(this).attr('title') + ' ';
                        layui.focusInsert(editor[0], 'face' + title);
                        editor.trigger('keyup');
                    });
                }
                , picture: function (editor) { //插入图片
                    layer.open({
                        type: 1
                        , id: 'fly-jie-upload'
                        , title: '插入图片'
                        , area: 'auto'
                        , shade: false
                        , area: '465px'
                        , fixed: false
                        , offset: [
                            editor.offset().top - $(window).scrollTop() + 'px'
                            , editor.offset().left + 'px'
                        ]
                        , skin: 'layui-layer-border'
                        , content: ['<ul class="layui-form layui-form-pane" style="margin: 20px;">'
                            , '<li class="layui-form-item">'
                            , '<label class="layui-form-label">URL</label>'
                            , '<div class="layui-input-inline">'
                            , '<input required name="image" placeholder="支持直接粘贴远程图片地址" value="" class="layui-input">'
                            , '</div>'
                            , '<button type="button" class="layui-btn layui-btn-primary" id="uploadImg"><i class="layui-icon">&#xe67c;</i>上传图片</button>'
                            , '</li>'
                            , '<li class="layui-form-item" style="text-align: center;">'
                            , '<button type="button" lay-submit lay-filter="uploadImages" class="layui-btn">确认</button>'
                            , '</li>'
                            , '</ul>'].join('')
                        , success: function (layero, index) {
                            var image = layero.find('input[name="image"]');

                            //执行上传实例
                            upload.render({
                                elem: '#uploadImg'
                                , url: '/api/upload/'
                                , size: 300000000
                                , done: function (res) {
                                    if (res.status == 0) {
                                        image.val(res.url);
                                    } else {
                                        layer.msg(res.msg, {icon: 5});
                                    }
                                }
                            });

                            form.on('submit(uploadImages)', function (data) {
                                var field = data.field;
                                if (!field.image) return image.focus();
                                layui.focusInsert(editor[0], 'img[' + field.image + '] ');
                                layer.close(index);
                                editor.trigger('keyup');
                            });
                        }
                    });
                }
                , href: function (editor) { //超链接
                    layer.prompt({
                        title: '请输入合法链接'
                        , shade: false
                        , fixed: false
                        , id: 'LAY_flyedit_href'
                        , offset: [
                            editor.offset().top - $(window).scrollTop() + 1 + 'px'
                            , editor.offset().left + 1 + 'px'
                        ]
                    }, function (val, index, elem) {
                        if (!/^http(s*):\/\/[\S]/.test(val)) {
                            layer.tips('请务必 http 或 https 开头', elem, {tips: 1})
                            return;
                        }
                        layui.focusInsert(editor[0], ' a(' + val + ')[' + val + '] ');
                        layer.close(index);
                        editor.trigger('keyup');
                    });
                }
                , quote: function (editor) { //引用
                    layer.prompt({
                        title: '请输入引用内容'
                        , formType: 2
                        , maxlength: 10000
                        , shade: false
                        , id: 'LAY_flyedit_quote'
                        , offset: [
                            editor.offset().top - $(window).scrollTop() + 1 + 'px'
                            , editor.offset().left + 1 + 'px'
                        ]
                        , area: ['300px', '100px']
                    }, function (val, index, elem) {
                        layui.focusInsert(editor[0], '[quote]\n  ' + val + '\n[/quote]\n');
                        layer.close(index);
                        editor.trigger('keyup');
                    });
                }
                , code: function (editor) { //插入代码
                    layer.prompt({
                        title: '请贴入代码'
                        , formType: 2
                        , maxlength: 10000
                        , shade: false
                        , id: 'LAY_flyedit_code'
                        , area: ['800px', '360px']
                    }, function (val, index, elem) {
                        layui.focusInsert(editor[0], '[pre]\n' + val + '\n[/pre]\n');
                        layer.close(index);
                        editor.trigger('keyup');
                    });
                }
                , hr: function (editor) { //插入水平分割线
                    layui.focusInsert(editor[0], '[hr]\n');
                    editor.trigger('keyup');
                }
                , preview: function (editor, span) { //预览
                    var othis = $(span), getContent = function () {
                        var content = editor.val();
                        return /^\{html\}/.test(content)
                            ? content.replace(/^\{html\}/, '')
                            : fly.content(content)
                    }, isMobile = device.ios || device.android;

                    if (mod.preview.isOpen) return layer.close(mod.preview.index);

                    mod.preview.index = layer.open({
                        type: 1
                        , title: '预览'
                        , shade: false
                        , offset: 'r'
                        , id: 'LAY_flyedit_preview'
                        , area: [
                            isMobile ? '100%' : '775px'
                            , '100%'
                        ]
                        , scrollbar: isMobile ? false : true
                        , anim: -1
                        , isOutAnim: false
                        , content: '<div class="detail-body layui-text" style="margin:20px;">' + getContent() + '</div>'
                        , success: function (layero) {
                            editor.on('keyup', function (val) {
                                layero.find('.detail-body').html(getContent());
                            });
                            mod.preview.isOpen = true;
                            othis.addClass('layui-this');
                        }
                        , end: function () {
                            delete mod.preview.isOpen;
                            othis.removeClass('layui-this');
                        }
                    });
                }
            };

            layui.use('face', function (face) {
                options = options || {};
                fly.faces = face;
                $(options.elem).each(function (index) {
                    var that = this, othis = $(that), parent = othis.parent();
                    parent.prepend(html);
                    parent.find('.fly-edit span').on('click', function (event) {
                        var type = $(this).attr('type');
                        mod[type].call(that, othis, this);
                        if (type === 'face') {
                            event.stopPropagation()
                        }
                    });
                });
            });

        }

        , escape: function (html) {
            return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
        }

        //内容转义
        , content: function (content) {
            var util = fly
                , item = fly.faces;

            //支持的html标签
            var html = function (end) {
                return new RegExp('\\n*\\|\\-' + (end || '') + '(div|span|p|button|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\-\\|\\n*', 'g');
            };


            //XSS
            content = util.escape(content || '')

                //转义图片
                .replace(/img\[([^\s]+?)\]/g, function (img) {
                    return '<img src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
                })

                //转义@
                .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;" class="fly-aite">$1</a>$2')

                //转义表情
                .replace(/face\[([^\s\[\]]+?)\]/g, function (face) {
                    var alt = face.replace(/^face/g, '');
                    return '<img alt="' + alt + '" title="' + alt + '" src="' + item[alt] + '">';
                })

                //转义脚本
                .replace(/a(\(javascript:)(.+)(;*\))/g, 'a(javascript:layer.msg(\'非法脚本\');)')

                //转义链接
                .replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) {
                    var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                    var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                    if (!href) return str;
                    var rel = /^(http(s)*:\/\/)\b(?!(\w+\.)*(sentsin.com|layui.com))\b/.test(href.replace(/\s/g, ''));
                    return '<a href="' + href + '" target="_blank"' + (rel ? ' rel="nofollow"' : '') + '>' + (text || href) + '</a>';
                })

                //转义横线
                .replace(/\[hr\]\n*/g, '<hr>')

                //转义表格
                .replace(/\[table\]([\s\S]*)\[\/table\]\n*/g, function (str) {
                    return str.replace(/\[(thead|th|tbody|tr|td)\]\n*/g, '<$1>')
                        .replace(/\n*\[\/(thead|th|tbody|tr|td)\]\n*/g, '</$1>')

                        .replace(/\[table\]\n*/g, '<table class="layui-table">')
                        .replace(/\n*\[\/table\]\n*/g, '</table>');
                })

                //转义 div/span
                .replace(/\n*\[(div|span)([\s\S]*?)\]([\s\S]*?)\[\/(div|span)\]\n*/g, function (str) {
                    return str.replace(/\[(div|span)([\s\S]*?)\]\n*/g, '<$1 $2>')
                        .replace(/\n*\[\/(div|span)\]\n*/g, '</$1>');
                })

                //转义列表
                .replace(/\[ul\]([\s\S]*)\[\/ul\]\n*/g, function (str) {
                    return str.replace(/\[li\]\n*/g, '<li>')
                        .replace(/\n*\[\/li\]\n*/g, '</li>')

                        .replace(/\[ul\]\n*/g, '<ul>')
                        .replace(/\n*\[\/ul\]\n*/g, '</ul>');
                })

                //转义代码
                .replace(/\[pre\]([\s\S]*)\[\/pre\]\n*/g, function (str) {
                    return str.replace(/\[pre\]\n*/g, '<pre>')
                        .replace(/\n*\[\/pre\]\n*/g, '</pre>');
                })

                //转义引用
                .replace(/\[quote\]([\s\S]*)\[\/quote\]\n*/g, function (str) {
                    return str.replace(/\[quote\]\n*/g, '<div class="layui-elem-quote">')
                        .replace(/\n*\[\/quote\]\n*/g, '</div>');
                })

                //转义换行
                .replace(/\n/g, '<br>')

            return content;
        }
    };

    //加载扩展模块
    layui.config({
        base: fly.dir
    }).extend({
        im: 'im',
        face: 'face',
    });

    //加载编辑器
    fly.layEditor({
        elem: '.fly-editor'
    });

    exports('fly', fly);

});